package com.example.yskjproject.view.dialog;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.tu.loadingdialog.LoadingDailog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.yskjproject.R;
import com.example.yskjproject.adapter.PicVideoAdapter;
import com.example.yskjproject.adapter.TagAdapter;
import com.example.yskjproject.content.Content;
import com.example.yskjproject.http.APIService;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.http.callback.JsonCallback;
import com.example.yskjproject.model.CreateWorksModel;
import com.example.yskjproject.model.LeftMenuModel;
import com.example.yskjproject.model.LeftModel;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.model.RoomLiveInfoModel;
import com.example.yskjproject.model.RoomOneLiveInfoModel;
import com.example.yskjproject.model.WorkInfoModel;
import com.example.yskjproject.ui.activity.ClassroomWorksActivity;
import com.example.yskjproject.utils.GenerateTestUserSig;
import com.example.yskjproject.utils.GlideLoader;
import com.example.yskjproject.utils.KeyboardUtils;
import com.example.yskjproject.utils.Log;
import com.example.yskjproject.utils.LogUtils;
import com.example.yskjproject.utils.SpCashUtils;
import com.example.yskjproject.utils.cos.CosServiceFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.cos.xml.CosXmlService;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.transfer.COSXMLUploadTask;
import com.tencent.cos.xml.transfer.TransferConfig;
import com.tencent.cos.xml.transfer.TransferManager;
import com.tencent.cos.xml.transfer.TransferState;
import com.tencent.cos.xml.utils.StringUtils;
import com.tencent.qcloud.tuicore.TUILogin;
import com.tencent.qcloud.tuicore.interfaces.TUICallback;
import com.tencent.qcloud.tuicore.util.ToastUtil;
import com.xzh.imagepicker.ImagePicker;
import com.xzh.imagepicker.bean.MediaFile;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * WorkDialogHelper  创建和进入工作室
 * <p>
 * 作者：zx
 * 创建时间：2024/4/24
 */
public class WorkDialogHelper extends Dialog {

    public static int REQUEST_SELECT_IMAGES_CODE = 0x01;

    private List<LeftMenuModel> listLabel = Lists.newArrayList();
    private FragmentActivity activity;
    private Context context;
    private IntentFilter filter;
    private NetworkCHangeReceive mbcr;

    private PicVideoAdapter picVideoAdapter;

    List<WorkInfoModel.StudioInfoBean.MediaListBean> mediaList;
    private static List<MediaFile> listMedia = Lists.newArrayList();


    private static List<MediaFile> listRMedia = Lists.newArrayList();

    private String isCreateOrUpdate;

    private CosXmlService cosXmlService;
    private TransferManager transferManager;
    private COSXMLUploadTask cosxmlTask;
    private String path;
    private List<Map<String, Object>> lisPath = Lists.newArrayList();


    private AppCompatImageView disSelectImg;
    private VideoView videoView;
    private AppCompatImageView videoBg;
    private RelativeLayout videoLayout;
    private AppCompatTextView tvTitle;
    private AppCompatButton btnCreateLogin;

    private AppCompatImageButton startVideo;


    //--tag
    private TagAdapter tagAdapter;
    private List<Integer> levleSelect = Lists.newArrayList();

    private List<Integer> levleSelectCan = Lists.newArrayList();

    private List<LeftMenuModel> listLabel2 = Lists.newArrayList();

    private List<Integer> levleSelectCan2 = Lists.newArrayList();
    private TagAdapter tagAdapter2;
    private List<Integer> levleSelect2 = Lists.newArrayList();

    MyProgressDialog custom1;

    private Gson gson = new Gson();
    private AppCompatTextView edName, edIntroduction;
    private int mCoverImageHeight = 0;
    private int mCoverImageWidth = 0;
    private LoadingDailog.Builder loadBuilder;
    private LoadingDailog loadingDailog;

    public WorkDialogHelper(@NonNull Context context, FragmentActivity activity, String isCreateOrUpdate) {
        super(context);
        this.context = context;
        this.activity = activity;
        this.isCreateOrUpdate = isCreateOrUpdate;
        setContentView(R.layout.works_dialog);
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        int layoutWidth;
        int layoutHeight;
        if (window != null) {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int screenWidth = displayMetrics.widthPixels;
            int screenHeight = displayMetrics.heightPixels;

            // 打印尺寸
            LogUtils.d("ScreenSize" + "Width: " + screenWidth + ", Height: " + screenHeight);
            if (screenWidth > 3000) {
                 layoutWidth = (int) (screenWidth * 0.65f);
                 layoutHeight = (int) (screenHeight * 0.68f); // 保持原始宽高比
            } else {
                layoutWidth = (int) (screenWidth * 0.9f);
                layoutHeight = (int) (screenHeight * 0.4f);
            }
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.width = layoutWidth;
            layoutParams.height = layoutHeight;
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            window.setAttributes(layoutParams);
        }
        custom1 = new MyProgressDialog(context, R.style.CustomTheme);//R.style.CustomTheme自定义加载动画圈的颜色
        tvTitle = findViewById(R.id.tv_title);
        btnCreateLogin = findViewById(R.id.btn_create_login);
        if (isCreateOrUpdate.equals("create")) {
            tvTitle.setText("创建我的工作室");
            btnCreateLogin.setText("创建并进入");
        } else if (isCreateOrUpdate.equals("setting")) {
            tvTitle.setText("设置我的工作室");
            btnCreateLogin.setText("确定");
            new Thread(() -> getWorksInfo()).start();
        } else if (isCreateOrUpdate.equals("studioPeople")) {
            tvTitle.setText("查看工作室");
            btnCreateLogin.setText("确定");
            findViewById(R.id.btn_cancel).setVisibility(View.GONE);
            findViewById(R.id.kj_name_btn).setVisibility(View.GONE);
            findViewById(R.id.kj_introduction_btn).setVisibility(View.GONE);
            new Thread(() -> getWorksInfo()).start();
        } else {
            tvTitle.setText("设置我的工作室");
            btnCreateLogin.setText("进入");
            new Thread(() -> getWorksInfo()).start();
        }

        cosXmlService = CosServiceFactory.getCosXmlService(context, Content.region, true);
        TransferConfig transferConfig = new TransferConfig.Builder().build();
        transferManager = new TransferManager(cosXmlService, transferConfig);


        disSelectImg = findViewById(R.id.dis_select_img);
        videoView = findViewById(R.id.video_view);
        videoBg = findViewById(R.id.video_bg);
        videoLayout = findViewById(R.id.video_layout);
        startVideo = findViewById(R.id.start_video);

        mbcr = new NetworkCHangeReceive();
        filter = new IntentFilter();
        filter.addAction("com.android.BroadcastReceiver");
//        context.registerReceiver(mbcr, filter);// 注册
        ContextCompat.registerReceiver(context, mbcr, filter, Context.RECEIVER_NOT_EXPORTED);

        setCanceledOnTouchOutside(false);
        findViewById(R.id.img_colose).setOnClickListener(close -> dismiss());
        setDateInfo();
    }

    /**
     * 获取工作室详情
     */
    private void getWorksInfo() {
        Type type = new TypeToken<LzyResponse<WorkInfoModel>>() {
        }.getType();
        APIService.<LzyResponse<WorkInfoModel>>getData(type, Urls.WORK_INFO + "?studio_id=" + SpCashUtils.getInstance().getWorkId()).subscribeOn(Schedulers.io()).map(response -> response.data).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<WorkInfoModel>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.e("onSubscribe ： " + d);
            }

            @SuppressLint({"NotifyDataSetChanged", "UseRequireInsteadOfGet"})
            @Override
            public void onNext(WorkInfoModel workInfoModel) {
                if (workInfoModel == null) {
                    return;
                }

                edName.setText(workInfoModel.getStudio_info().getTitle());
                edIntroduction.setText(workInfoModel.getStudio_info().getDescription());
                mediaList = workInfoModel.getStudio_info().getMedia_list();
                for (WorkInfoModel.StudioInfoBean.MediaListBean bean : workInfoModel.getStudio_info().getMedia_list()) {
                    listMedia.add(new MediaFile(bean.getMedia_url(), bean.getMedia_type()));
                }
                if (!listMedia.isEmpty()) {
                    Glide.with(context).load(listMedia.get(0).getPath())
                            .addListener(new RequestListener<Drawable>(){
                                @Override
                                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                    return false;
                                }

                                @Override
                                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                    mCoverImageWidth = resource.getIntrinsicWidth();
                                    mCoverImageHeight = resource.getIntrinsicHeight();
                                    return false;
                                }
                            })
                            .apply(RequestOptions.bitmapTransform(new RoundedCorners(20)))//圆角半径
                            .into(disSelectImg);
                    picVideoAdapter.notifyDataSetChanged();
                }

                if (!workInfoModel.getStudio_info().getTag_lv2_id().isEmpty()) {
                    levleSelectCan.clear();
                    levleSelectCan.addAll(workInfoModel.getStudio_info().getTag_lv2_id());
                    getLevel2();
                }

                if (!workInfoModel.getStudio_info().getTag_lv3_id().isEmpty()) {
                    levleSelectCan2.clear();
                    levleSelectCan2.addAll(workInfoModel.getStudio_info().getTag_lv3_id());
                     getLevel3();
                }

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();            //请求失败
                Log.e("onError ： " + "获取失败");
            }

            @Override
            public void onComplete() {

            }
        }); //
    }

    /**
     * 设置我的工作室内容
     */
    @SuppressLint({"NotifyDataSetChanged", "NonConstantResourceId"})
    private void setDateInfo() {
        findViewById(R.id.btn_cancel).setOnClickListener(exit -> {
            dismiss();
        });
        //name
        edName = findViewById(R.id.ed_name);
        findViewById(R.id.kj_name_btn).setOnClickListener(name -> {
            showEditWorkSpaceInfo(1);
        });
        //简介
        edIntroduction = findViewById(R.id.ed_introduction);
        findViewById(R.id.kj_introduction_btn).setOnClickListener(name -> {
            showEditWorkSpaceInfo(2);
        });
        edIntroduction.setOnEditorActionListener((v, actionId, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                edIntroduction.setFocusable(false);
                edIntroduction.setFocusableInTouchMode(false);
                findViewById(R.id.kj_introduction_btn).setVisibility(View.VISIBLE);
                KeyboardUtils.hideSoftInput(edIntroduction);
                return true;
            }
            return false;
        });
        //第一级标签
        RecyclerView rvLabel = findViewById(R.id.rv_label);
        rvLabel.setLayoutManager(new GridLayoutManager(context, 4));
        tagAdapter = new TagAdapter(context, listLabel);
        rvLabel.setAdapter(tagAdapter);
        //第一级展开
//        r1_bt = findViewById(R.id.r1_bt);
        tagAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (isCreateOrUpdate.equals("studioPeople")){
                return;
            }
            if (listLabel.get(position).isSelect()) {
                listLabel.get(position).setSelect(false);
                for (int i = 0; i < levleSelect.size(); i++) {
                    if (levleSelect.get(i) == listLabel.get(position).getId()) {
                        levleSelect.remove(i);
                    }
                }
            } else {
                listLabel.get(position).setSelect(true);
                levleSelect.add(listLabel.get(position).getId());
            }
            tagAdapter.notifyDataSetChanged();
        });
        if (isCreateOrUpdate.equals("create")) {
            new Thread(() -> getLevel2()).start();
        }


        //第2级标签
        RecyclerView rvLabel2 = findViewById(R.id.rv_label2);
        // 创建FlexboxLayoutManager实例
        rvLabel2.setLayoutManager(new GridLayoutManager(context, 4));
        tagAdapter2 = new TagAdapter(context, listLabel2);
        rvLabel2.setAdapter(tagAdapter2);
        tagAdapter2.setOnItemChildClickListener((adapter, view, position) -> {
            if (isCreateOrUpdate.equals("studioPeople")){
                return;
            }
            if (listLabel2.get(position).isSelect()) {
                listLabel2.get(position).setSelect(false);
                for (int i = 0; i < levleSelect2.size(); i++) {
                    if (levleSelect2.get(i) == listLabel2.get(position).getId()) {
                        levleSelect2.remove(i);
                    }
                }

            } else {
                listLabel2.get(position).setSelect(true);
                levleSelect2.add(listLabel2.get(position).getId());
            }
            tagAdapter2.notifyDataSetChanged();
        });
        if (isCreateOrUpdate.equals("create")) {
            new Thread(() -> getLevel3()).start();
        }
        findViewById(R.id.add_pic_vid).setOnClickListener(add -> {
            // 同时选择图片和视频
            ImagePicker.getInstance().setTitle("相册与视频").showImage(true)//设置是否展示图片
                    .showVideo(true)//设置是否展示视频
                    .setMaxCount(6)//设置最大选择图片数目(默认为1，单选)
                    .setImageLoader(new GlideLoader()).start(activity, REQUEST_SELECT_IMAGES_CODE);
        });

        RecyclerView rvPicVideo = findViewById(R.id.rv_pic_video);
        rvPicVideo.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        if (isCreateOrUpdate.equals("studioPeople")){
            picVideoAdapter = new PicVideoAdapter(listMedia, context, "other");
        }else{
            picVideoAdapter = new PicVideoAdapter(listMedia, context, null);
        }

        rvPicVideo.setAdapter(picVideoAdapter);
        picVideoAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @SuppressLint({"ResourceType", "NewApi"})
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.delect_img) {
                    listMedia.remove(position);
                    if (!listMedia.isEmpty()) {
                        Glide.with(context).load(listMedia.get(0).getPath())//圆角半径
                                .into(disSelectImg);
                    } else {
                        Glide.with(context).load(context.getColor(R.color.white))//圆角半径
                                .into(disSelectImg);
                    }
                } else if (view.getId() == R.id.item_pic_video) {
                    if (!listMedia.isEmpty()) {
                        if (listMedia.get(position).getFolderName().equals("video") || listMedia.get(position).getFolderName().equals("Movies")) {
                            disSelectImg.setVisibility(View.GONE);
                            videoLayout.setVisibility(View.VISIBLE);
                            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                            try {
                                retriever.setDataSource(listRMedia.get(position).getPath()); // videoPath 是视频文件的路径
                                Bitmap firstFrame = retriever.getFrameAtTime(0);
                                Glide.with(context).load(firstFrame).apply(RequestOptions.bitmapTransform(new RoundedCorners(40)))//圆角半径
                                        .into(videoBg);
                            } catch (IllegalArgumentException e) {
                                e.printStackTrace();
                            } finally {
                                try {
                                    retriever.release();
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                            videoView.setVideoPath(listMedia.get(position).getPath());
                        } else {
                            disSelectImg.setVisibility(View.VISIBLE);
                            videoLayout.setVisibility(View.GONE);
                            Glide.with(context).load(listMedia.get(position).getPath())//圆角半径
                                    .into(disSelectImg);
                        }
                    }
                }
                picVideoAdapter.notifyDataSetChanged();
            }
        });

        startVideo.setOnClickListener(start -> {
            videoBg.setVisibility(View.GONE);
            videoView.start();
        });


        btnCreateLogin.setOnClickListener(createLogin -> {
            if (isCreateOrUpdate.equals("studioPeople")) {
                dismiss();
            } else {
                custom1.show();
                String nameTitle = Objects.requireNonNull(edName.getText()).toString().trim();
                String edIntroductio = Objects.requireNonNull(edIntroduction.getText()).toString().trim();
                if (TextUtils.isEmpty(nameTitle)) {
                    ToastUtil.toastShortMessage("工作室名称不能为空!");
                    custom1.hide();
                    return;
                }
                if (TextUtils.isEmpty(edIntroductio)) {
                    ToastUtil.toastShortMessage("简介不能为空!");
                    custom1.hide();
                    return;
                }
                if (levleSelect.isEmpty()) {
                    ToastUtil.toastShortMessage("一级标签未被选择!");
                    custom1.hide();
                    return;
                }
                if (levleSelect2.isEmpty()) {
                    ToastUtil.toastShortMessage("二级标签未被选择!");
                    custom1.hide();
                    return;
                }
                //上传视频和图片
                if (!listRMedia.isEmpty()) {
                    loadBuilder = new LoadingDailog.Builder(getContext())
                            .setMessage("加载中，请稍后。。")
                            .setCancelable(false)
                            .setCancelOutside(false);
                    if (loadingDailog == null) {
                        loadingDailog = loadBuilder.create();
                        loadingDailog.show();
                    }
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for (int i = 0; i < listRMedia.size(); i++) {
                                MediaFile mediaFile = listRMedia.get(i);

                                if (mediaFile.getFolderName().equals("Pictures") || mediaFile.getFolderName().equals("picture")) {
                                    try {
                                        cosxmlTask = transferManager.upload(Content.bucket, Content.getCosPicturePath(i), mediaFile.getPath(), null);
                                        cosxmlTask.setCosXmlResultListener(new CosXmlResultListener() {
                                            @Override
                                            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                                                if (loadingDailog != null) {
                                                    loadingDailog.dismiss();
                                                }
                                                android.util.Log.d("QCloudHttp", "upload Success");
                                                COSXMLUploadTask.COSXMLUploadTaskResult cOSXMLUploadTaskResult = (COSXMLUploadTask.COSXMLUploadTaskResult) result;
                                                cosxmlTask = null;
                                                path = cOSXMLUploadTaskResult.accessUrl;
                                                if (!TextUtils.isEmpty(path)) {
                                                    Map<String, Object> picMap = Maps.newHashMap();
                                                    picMap.put("media_url", path);
                                                    picMap.put("media_type", "picture");
                                                    picMap.put("height",mCoverImageHeight);
                                                    picMap.put("width",mCoverImageWidth);
                                                    lisPath.add(picMap);
                                                    if (lisPath.size() == listRMedia.size()) {
                                                        han.sendEmptyMessage(1000);
                                                    }
                                                    task.trigger();
                                                }
                                            }

                                            @Override
                                            public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) {
                                                android.util.Log.d("QCloudHttp", "upload Fail");
                                                if (loadingDailog != null) {
                                                    loadingDailog.dismiss();
                                                }
                                                Log.e("cos:" + "上传失败");
                                                ToastUtil.toastShortMessage("图片上传失败");
                                                han.sendEmptyMessage(-1);
                                                if (cosxmlTask.getTaskState() != TransferState.PAUSED) {
                                                    cosxmlTask = null;
                                                }
                                                if (exception != null) {
                                                    exception.printStackTrace();
                                                }
                                                if (serviceException != null) {
                                                    serviceException.printStackTrace();
                                                }
                                            }
                                        });
                                        task.await();
                                    } catch (InterruptedException e) {
                                        throw new RuntimeException(e);
                                    }

                                }

                                if (mediaFile.getFolderName().equals("video") || mediaFile.getFolderName().equals("Movies")) {
                                    try {
                                        cosxmlTask = transferManager.upload(Content.bucket, Content.cosVideoPath, mediaFile.getPath(), null);
                                        cosxmlTask.setCosXmlResultListener(new CosXmlResultListener() {
                                            @Override
                                            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                                                android.util.Log.d("QCloudHttp", "upload Success");
                                                COSXMLUploadTask.COSXMLUploadTaskResult cOSXMLUploadTaskResult = (COSXMLUploadTask.COSXMLUploadTaskResult) result;
                                                cosxmlTask = null;
                                                path = cOSXMLUploadTaskResult.accessUrl;
                                                if (!TextUtils.isEmpty(path)) {
                                                    Map<String, Object> picMap = Maps.newHashMap();
                                                    picMap.put("media_url", path);
                                                    picMap.put("media_type", "video");
                                                    picMap.put("height",mCoverImageHeight);
                                                    picMap.put("width",mCoverImageWidth);
                                                    lisPath.add(picMap);
                                                    if (lisPath.size() == listRMedia.size()) {
                                                        han.sendEmptyMessage(1000);
                                                    }
                                                    task.trigger();
                                                }
                                            }


                                            @Override
                                            public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) {
                                                android.util.Log.d("QCloudHttp", "upload Fail");
                                                Log.e("cos:" + "上传失败");
                                                han.sendEmptyMessage(-2);
                                                if (cosxmlTask.getTaskState() != TransferState.PAUSED) {
                                                    cosxmlTask = null;
                                                }
                                                if (exception != null) {
                                                    exception.printStackTrace();
                                                }
                                                if (serviceException != null) {
                                                    serviceException.printStackTrace();
                                                }
                                            }
                                        });
                                        task.await();
                                    } catch (InterruptedException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                            }
                        }
                    }).start();

                } else {
                    if (!listMedia.isEmpty()) {
                        if (isCreateOrUpdate.equals("login") || isCreateOrUpdate.equals("setting") && mediaList.size() == listMedia.size()) {
                            han.sendEmptyMessage(1000);
                        }
                    } else {
                        custom1.hide();
                        ToastUtil.toastShortMessage("请选择图片或者视频");
                    }
                }
            }

        });
    }

    private void showEditWorkSpaceInfo(int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View dialogView = getLayoutInflater().inflate(R.layout.workbase_edit, null);
        builder.setView(dialogView);
        final AlertDialog dialogProgress = builder.create();
        dialogProgress.setCancelable(false);
        EditText et_workstation_info = dialogView.findViewById(R.id.et_workstation_info);
        if (type == 1) {
            et_workstation_info.setMaxEms(30);
            et_workstation_info.setHint("请输入工作室名称");
        } else {
            et_workstation_info.setMaxEms(100);
            et_workstation_info.setHint("请输入工作室简介");
        }
        Button btn_format = dialogView.findViewById(R.id.btn_format);
        btn_format.setOnClickListener(view -> {
            if (TextUtils.isEmpty(et_workstation_info.getText())) {
                if (type == 1) {
                    ToastUtil.toastShortMessage("工作室名称不能为空");
                } else {
                    ToastUtil.toastShortMessage("工作室简介不能为空");
                }
            } else {
                if (type == 1) {
                    edName.setText(et_workstation_info.getText().toString());
                } else {
                    edIntroduction.setText(et_workstation_info.getText().toString());
                }
            }
            dialogProgress.dismiss();
        });

        dialogProgress.show();
    }

    private static Task task = new Task();

    private static class Task {
        private boolean ready = false;

        public synchronized void await() throws InterruptedException {
            while (!ready) {
                wait(); // 等待条件满足
            }
            ready = false; // 重置条件，为下一次等待做准备
        }

        public synchronized void trigger() {
            ready = true;
            notifyAll(); // 通知所有等待的线程
        }
    }


    @SuppressLint("HandlerLeak")
    Handler han = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1000:
                    if (!listMedia.isEmpty()) {
                        for (int i = listMedia.size() - 1; i >= 0; i--) {
                            if (listMedia.get(i).getMime() != null) {
                                listMedia.remove(i);
                            }
                        }
                        for (int i2 = 0; i2 < listMedia.size(); i2++) {
                            Map<String, Object> picMap = Maps.newHashMap();
                            picMap.put("media_url", listMedia.get(i2).getPath());
                            picMap.put("height",mCoverImageHeight);
                            picMap.put("width",mCoverImageWidth );
                            if (listMedia.get(i2).getFolderName().equals("picture") || listMedia.get(i2).getFolderName().equals("Pictures")) {
                                picMap.put("media_type", "picture");
                            } else {
                                picMap.put("media_type", "video");
                            }
                            lisPath.add(picMap);
                        }
                    }
                    listRMedia.clear();
                    getCreateWorks(lisPath);
                    break;
                case -1:
                    ToastUtil.toastShortMessage("图片上传失败");
                    custom1.hide();
                    break;
                case -2:
                    ToastUtil.toastShortMessage("视频上传失败");
                    custom1.hide();
                    break;
            }
        }
    };

    //todo 创建直播
    private void tikLogin(int studioId) {
        if (isCreateOrUpdate.equals("create")) {
            OkGo.<LzyResponse<RoomOneLiveInfoModel>>get(Urls.LIVE_INFO + "?studio_id=" + studioId).execute(new JsonCallback<LzyResponse<RoomOneLiveInfoModel>>() {
                @Override
                public void onSuccess(Response<LzyResponse<RoomOneLiveInfoModel>> response) {
                    RoomOneLiveInfoModel data = response.body().data;
                    if (data == null) {
                        return;
                    }
                    TUILogin.login(context, Content.SDK_ID,     // 请替换为步骤一取到的 SDKAppID
                            data.getLive_user_id(),        // 请替换为您的 UserID
                            GenerateTestUserSig.genTestUserSig(String.valueOf(data.getLive_user_id())),  // 您可以在控制台中计算一个 UserSig 并填在这个位置
                            new TUICallback() {
                                @Override
                                public void onSuccess() {
                                    custom1.hide();
                                    LoginDirectSeedingOneHome(data);
                                    dismiss();
                                }

                                @SuppressLint("CheckResult")
                                @Override
                                public void onError(int errorCode, String errorMessage) {
                                    custom1.hide();
                                    ToastUtil.toastShortMessage(errorMessage);
                                }

                            });

                }

                @Override
                public void onError(Response<LzyResponse<RoomOneLiveInfoModel>> response) {
                    super.onError(response);
                }
            });

        } else {
            OkGo.<LzyResponse<RoomLiveInfoModel>>get(Urls.LIVE_INFO + "?studio_id=" + studioId).execute(new JsonCallback<LzyResponse<RoomLiveInfoModel>>() {
                @Override
                public void onSuccess(Response<LzyResponse<RoomLiveInfoModel>> response) {
                    RoomLiveInfoModel data = response.body().data;
                    if (data == null) {
                        return;
                    }
                    TUILogin.login(context, Content.SDK_ID,     // 请替换为步骤一取到的 SDKAppID
                            data.getLive_user_id(),        // 请替换为您的 UserID
                            GenerateTestUserSig.genTestUserSig(String.valueOf(data.getLive_user_id())),  // 您可以在控制台中计算一个 UserSig 并填在这个位置
                            new TUICallback() {
                                @Override
                                public void onSuccess() {
                                    custom1.hide();
                                    LoginDirectSeedingHome(data);
                                    dismiss();
                                }

                                @SuppressLint("CheckResult")
                                @Override
                                public void onError(int errorCode, String errorMessage) {
                                    custom1.hide();
                                    ToastUtil.toastShortMessage(errorMessage);
                                }

                            });

                }

                @Override
                public void onError(Response<LzyResponse<RoomLiveInfoModel>> response) {
                    super.onError(response);
                }
            });
        }

    }


    /**
     * 上传完图片上传信息 创建工作室
     */
    private void getCreateWorks(List<Map<String, Object>> lisPath) {
        Map<String, Object> jsonParams = new HashMap<>();
        String nameTitle = edName.getText().toString().trim();
        String edIntroductio = edIntroduction.getText().toString().trim();
        jsonParams.put("title", nameTitle);
        jsonParams.put("description", edIntroductio);
        jsonParams.put("media_list", lisPath);
        jsonParams.put("tag_lv2_id", levleSelect);
        jsonParams.put("tag_lv3_id", levleSelect2);
        String paramsDate = gson.toJson(jsonParams);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
        OkGo.<LzyResponse<CreateWorksModel>>post(Urls.CREATE_WORKS).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse<CreateWorksModel>>() {
            @Override
            public void onSuccess(Response<LzyResponse<CreateWorksModel>> response) {
                if (response.body().code == 0) {
                    if (response.body().data != null) {
                        if (isCreateOrUpdate.equals("setting")) {
                            //修改成功
                            ToastUtil.toastShortMessage("修改成功");
                            custom1.hide();
                            dismiss();
                        } else {
                            tikLogin(response.body().data.getStudio_info().getId());
                        }

                    }
                }
            }

            @Override
            public void onError(Response<LzyResponse<CreateWorksModel>> response) {
                super.onError(response);
                ToastUtil.toastShortMessage("创建失败");
            }
        });

    }

    /**
     * 创建直播  需要传递的数据
     */
    private void LoginDirectSeedingOneHome(RoomOneLiveInfoModel model) {
        Intent intent = new Intent(context, ClassroomWorksActivity.class);
        intent.putExtra("id", model.getLive_room_id());
        intent.putExtra("roomName", model.getStudio_info().getTitle());
        intent.putExtra("userName", model.getLive_user_name());
        intent.putExtra("userId",model.getLive_user_id());
        intent.putExtra("avatar_url", model.getAvatar_url());
        intent.putExtra("studioWork", model.getStudio_info().getId());
        intent.putExtra("enableSeatControl", false);
        intent.putExtra("muteMicrophone", !true);
        intent.putExtra("openCamera", true);
        intent.putExtra("soundOnSpeaker", true);
        intent.putExtra("isCreate", true);
        context.startActivity(intent);
    }


    /**
     * 进入直播间  需要传递的数据
     */
    private void LoginDirectSeedingHome(RoomLiveInfoModel model) {
        Intent intent = new Intent(context, ClassroomWorksActivity.class);
        intent.putExtra("id", model.getLive_room_id());
        intent.putExtra("roomName", model.getStudio_info().getTitle());
        intent.putExtra("userName", model.getLive_user_name());
        intent.putExtra("userId",model.getLive_user_id());
        intent.putExtra("avatar_url", model.getAvatar_url());
        intent.putExtra("studioWork", model.getStudio_info().getId());
        intent.putExtra("enableSeatControl", false);
        intent.putExtra("muteMicrophone", !true);
        intent.putExtra("openCamera", true);
        intent.putExtra("soundOnSpeaker", true);
        intent.putExtra("isCreate", true);
        context.startActivity(intent);
    }


    private void getLevel3() {
        Type type = new TypeToken<LzyResponse<LeftModel>>() {
        }.getType();
        APIService.<LzyResponse<LeftModel>>getData(type, Urls.LIST_LEVEL + "?level=3").subscribeOn(Schedulers.io()).map(response -> response.data).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<LeftModel>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.e("onSubscribe ： " + d);
            }

            @SuppressLint({"NotifyDataSetChanged", "UseRequireInsteadOfGet"})
            @Override
            public void onNext(LeftModel leftLevel2Model) {
                if (leftLevel2Model.getTag_list().isEmpty()) {
                    return;
                }

                listLabel2.clear();
                if (isCreateOrUpdate.equals("login") || isCreateOrUpdate.equals("setting") || isCreateOrUpdate.equals("studioPeople")) {
                    for (LeftMenuModel mode : leftLevel2Model.getTag_list()) {
                        if (!levleSelectCan2.isEmpty()) {
                            for (int id : levleSelectCan2) {
                                if (id == mode.getId()) {
                                    if (!listLabel2.contains(mode)) {
                                        mode.setSelect(true);
                                        listLabel2.add(mode);
                                        levleSelect2.add(id);
                                    }
                                } else {
                                    if (!listLabel2.contains(mode)) {
                                        mode.setSelect(false);
                                        listLabel2.add(mode);
                                    }
                                }
                            }
                        } else {
                            mode.setSelect(false);
                            listLabel2.add(mode);
                        }
                    }
                } else {
                    for (LeftMenuModel mode : leftLevel2Model.getTag_list()) {
                        mode.setSelect(false);
                        listLabel2.add(mode);
                    }
                }

                Log.e("listLabel22model==" + new Gson().toJson(listLabel2));
                tagAdapter2.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();            //请求失败
                Log.e("onError ： " + "获取失败");
            }

            @Override
            public void onComplete() {

            }
        }); //
    }


    private void getLevel2() {
        Type type = new TypeToken<LzyResponse<LeftModel>>() {
        }.getType();
        APIService.<LzyResponse<LeftModel>>getData(type, Urls.LIST_LEVEL + "?level=2").subscribeOn(Schedulers.io()).map(response -> response.data).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<LeftModel>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.e("onSubscribe ： " + d);
            }

            @SuppressLint({"NotifyDataSetChanged", "UseRequireInsteadOfGet"})
            @Override
            public void onNext(LeftModel leftLevel2Model) {
                if (leftLevel2Model.getTag_list().isEmpty()) {
                    return;
                }
                listLabel.clear();
                if (isCreateOrUpdate.equals("login") || isCreateOrUpdate.equals("setting") || isCreateOrUpdate.equals("studioPeople")) {
                    for (LeftMenuModel mode : leftLevel2Model.getTag_list()) {
                        if (!levleSelectCan.isEmpty()) {
                            for (int id : levleSelectCan) {
                                if (id == mode.getId()) {
                                    if (!listLabel.contains(mode)) {
                                        mode.setSelect(true);
                                        listLabel.add(mode);
                                        levleSelect.add(id);
                                    }
                                } else {
                                    if (!listLabel.contains(mode)) {
                                        mode.setSelect(false);
                                        listLabel.add(mode);
                                    }
                                }
                            }
                        } else {
                            mode.setSelect(false);
                            listLabel.add(mode);
                        }
                    }
                } else {
                    for (LeftMenuModel mode : leftLevel2Model.getTag_list()) {
                        mode.setSelect(false);
                        listLabel.add(mode);
                    }
                }

                tagAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();            //请求失败
                Log.e("onError ： " + "获取失败");
            }

            @Override
            public void onComplete() {

            }
        }); //
    }


    @Override
    public void dismiss() {
        super.dismiss();
        context.unregisterReceiver(mbcr);
        mbcr = null;
        listMedia.clear();
        levleSelectCan.clear();
        levleSelectCan2.clear();
    }

    public class NetworkCHangeReceive extends BroadcastReceiver {

        @SuppressLint("NotifyDataSetChanged")
        @Override
        public void onReceive(Context context, Intent intent) {
            listRMedia = (List<MediaFile>) intent.getSerializableExtra("mediaFiles");
            if (listRMedia.size() + listMedia.size() > 6) {
                ToastUtil.toastShortMessage("超过最大数量");
                return;
            }
            listMedia.addAll(listRMedia);
            picVideoAdapter.notifyDataSetChanged();
            if (!listRMedia.isEmpty()) {
                if (!StringUtils.isEmpty(listRMedia.get(0).getFolderName()) && listRMedia.get(0).getFolderName().equals("Movies")
                || listRMedia.get(0).getPath().contains(".mp4")) {
                    listRMedia.get(0).setFolderName("Pictures");
                    videoLayout.setVisibility(View.VISIBLE);
                    disSelectImg.setVisibility(View.GONE);
                    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                    try {
                        retriever.setDataSource(listRMedia.get(0).getPath()); // videoPath 是视频文件的路径
                        Bitmap firstFrame = retriever.getFrameAtTime(0);
                        Glide.with(context).load(firstFrame).apply(RequestOptions.bitmapTransform(new RoundedCorners(40)))//圆角半径
                                .into(videoBg);
                        videoView.setVideoPath(listRMedia.get(0).getPath());
                        // 使用获取到的第一帧图像
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            retriever.release();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                } else {
                    videoLayout.setVisibility(View.GONE);
                    disSelectImg.setVisibility(View.VISIBLE);
                    listRMedia.get(0).setFolderName("Pictures");
                    Glide.with(context).load(listRMedia.get(0).getPath()).apply(RequestOptions.bitmapTransform(new RoundedCorners(40)))//圆角半径
                            .addListener(new RequestListener<Drawable>(){
                                @Override
                                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                    return false;
                                }

                                @Override
                                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                    mCoverImageWidth = resource.getIntrinsicWidth();
                                    mCoverImageHeight = resource.getIntrinsicHeight();
                                    return false;
                                }
                            })
                            .into(disSelectImg);
                }

            }

        }
    }
}
